<template>
  <!--新增客户-->
  <el-dialog
    :title="cms"
    :visible.sync="dialogVisible8"
    :before-close="handleClose8"
    width="900px">
    <div>
      <el-form size="mini" :model="sendForm8" label-width="100px"  ref="sendForm8" :rules="rules8">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="公司名称：" prop="companyName">
              <el-input name="companyName" type="text" @change="getCompanyInfo" v-model="sendForm8.companyName"  autoComplete="on" ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="统一信用码：" prop="licenseCode">
              <el-input disabled v-model="sendForm8.licenseCode"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="注册地址：" >
              <el-input placeholder="开票信息地址" v-model="sendForm8.regAddress"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电话：" >
              <el-input placeholder="开票信息电话" v-model="sendForm8.regPhone"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="开户行：">
              <el-input placeholder="开票信息开户行" v-model="sendForm8.bankName"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="银行帐号：">
              <el-input placeholder="开票信息银行帐号" v-model="sendForm8.bankNumber"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="所在地区："  >
              <el-cascader
                ref="diQuIds"
                filterable
                clearable
                v-model="diQuIds"
                :props="{ value: 'areaId',label:'areaName',children:'children' }"
                :options="options"
                >
              </el-cascader>
            </el-form-item>
          </el-col>
        </el-row>

         <div style="margin-top: 20px">
        <svg-icon icon-class="marker" style="color: #606266"></svg-icon>
        <span class="font-small">联系人信息（<span style="color:Red">必须填一条</span>）</span>
         </div>
         <div>
        <el-table :data="sendForm8.contactsData" size="mini" :header-cell-style="{background:'#f8f8f9',color:'#80878f'}" border style="width: 100%;margin:20px 0">
          <el-table-column
            align="center"
            label="联系人"
            width="100">
            <template slot-scope="scope">
              <el-form-item style="margin-bottom: 0;" :prop="`contactsData.${scope.$index}.name`" :rules="rules8.linkman" label-width="0px">
                <el-input v-model="scope.row.name" style="width:100%" ></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            label="电话"
            width="130"
            align="center">
            <template slot-scope="scope">
              <el-form-item style="margin-bottom: 0;" :prop="`contactsData.${scope.$index}.mobile`" :rules="rules8.regPhone"  label-width="0px">
                <el-input v-model="scope.row.mobile" style="width:100%"  ></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            label="职务"
            width="100"
            align="center">
            <template slot-scope="scope">
              <el-form-item style="margin-bottom: 0;" :prop="`contactsData.${scope.$index}.position`"  label-width="0px">
                <el-input v-model="scope.row.position"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column   label="是否为主联系人" width="150" align="center">
            <template slot-scope="scope">
              <el-form-item style="margin-bottom: 0;" label-width="0px">
                <el-radio-group v-model="scope.row.is_main">
                  <el-radio :label="1">是</el-radio>
                  <el-radio :label="0">否</el-radio>
                </el-radio-group>
              </el-form-item>

            </template>
          </el-table-column>
          <el-table-column  label="备注" width="150" align="center">
            <template slot-scope="scope">
              <el-form-item style="margin-bottom: 0;" label-width="0px">
                <el-input v-model="scope.row.remarks" ></el-input>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column  label="操作" min-width="100" align="center" fixed="right">
            <template slot-scope="scope">
              <!-- <el-button type="text" @click="editContact(scope.$index)">编辑</el-button> -->
              <el-button type="text" size="mini" @click="delContact(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button type="primary" size="mini" @click="addContact">增加联系人</el-button>
         </div>

         <div style="margin-top: 40px">
        <svg-icon icon-class="marker" style="color: #606266"></svg-icon>
        <span class="font-small">收货地址（<span style="color:Red">必须填一条</span>）</span>
         </div>
         <div>
        <el-table :data="sendForm8.addressData" size="mini" :header-cell-style="{background:'#f8f8f9',color:'#80878f'}" border style="width: 100%;margin:20px 0">
          <el-table-column
            align="center"
            label="类型"
            width="120">
            <template slot-scope="scope">
              <el-form-item style="margin-bottom: 0;" :prop="`addressData.${scope.$index}.type`"  label-width="0px">
                <el-select v-model="scope.row.type" style="width: 100%" >
                  <el-option label="收货地址"  :value="1"></el-option>
                  <el-option label="发票地址"  :value="2"></el-option>
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            label="联系人"
            width="100"
            align="center">
            <template slot-scope="scope">
              <el-form-item style="margin-bottom: 0;" :prop="`addressData.${scope.$index}.contacts`" :rules="rules8.linkman" label-width="0px">
                <el-input v-model="scope.row.contacts" style="width:100%"  ></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            width="130"
            align="center"
            label="电话">
            <template slot-scope="scope">
              <el-form-item style="margin-bottom: 0;" label-width="0px" :prop="`addressData.${scope.$index}.mobile`" :rules="rules8.regPhone" >
               <el-input v-model="scope.row.mobile" ></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            label="所在地区"
            width="150"
            align="center">
            <template slot-scope="scope">
              <el-form-item  style="margin-bottom: 0;" :prop="`addressData.${scope.$index}.diQuIds`" :rules="rules8.diQuIds" label-width="0px">
                <el-cascader
                    filterable
                    clearable
                   :ref="'areaInfo'+scope.$index"
                    v-model="scope.row.diQuIds"
                    :props="{ value: 'areaId',label:'areaName',children:'children' }"
                    :options="options"></el-cascader>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column  label="详细地址" width="150" align="center">
            <template slot-scope="scope">
              <el-form-item  style="margin-bottom: 0;" label-width="0px">
                <el-input v-model="scope.row.address"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column   label="默认" min-width="150" align="center">
            <template slot-scope="scope">
              <el-form-item style="margin-bottom: 0;" label-width="0px">
                <el-radio-group v-model="scope.row.is_default">
                  <el-radio :label="1">是</el-radio>
                  <el-radio :label="0">否</el-radio>
                </el-radio-group>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column  label="操作" width="100" align="center" fixed="right">
            <template slot-scope="scope">
              <!-- <el-button type="text" @click="editContact(scope.$index)">编辑</el-button> -->
              <el-button type="text" size="mini" @click="delAddress(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button type="primary" size="mini" @click="addAddress">增加收货地址</el-button>
         </div>
       </el-form>
       </div>

    <span slot="footer" class="dialog-footer">
      <el-button @click="handleClose8">取 消</el-button>
      <el-button type="primary" @click="handleConfirm8" :loading="btnLoading8">确 认</el-button>
      </span>
  </el-dialog>
</template>
<script>
import {getAreaList,addCustomer,customerDetail,getCustomerCheckData} from '@/api/allInLine/inquiry'
import {validatePhone,validateLicenseCode} from '@/utils/validate';
import { mapGetters } from 'vuex'
import { Message } from 'element-ui';

const defaultSendForm8={
  companyName:'', //公司名称
  companyId:'',
  licenseCode:'', //统一信用码
  regAddress:'', //注册地址
  regPhone:'' , //电话
  bankName:'', //开户行
  bankNumber:'' , //银行账号
  contactsData:[],
  addressData:[],
  provinceId:'',
  cityId:'',
  areaId:'',
  areaInfo:[]
};

const defaultContactsItems = {name:'',mobile:'',position:'',is_main:0, remarks:''}
const defaultAddressItems = {type:'',contacts:'',province_id:'',city_id:'',area_id:'',area_info:'',mobile:'',is_default:0,address:'',diQuIds:[]}

export default {
  name: "index",
  data(){
      const isvalidatePhone = (rule, value, callback) => {
        if(!validatePhone(value)){
          callback(new Error('请输入正确的手机号'))
        } else {
          callback()
        }
      };
      const isvalidateLicenseCode = (rule, value, callback) => {
        if(!validateLicenseCode(value)){
          callback(new Error('请输入正确的手机号'))
        } else {
          callback()
        }
      };
    return {
      dialogVisible8:false,
      btnLoading8:false,
      sendForm8:JSON.parse(JSON.stringify(defaultSendForm8)),
      rules8:{
          linkman: [{required: true, trigger: 'blur',message: '请输入联系人'}],
          regPhone: [{required: true, trigger: 'blur', validator: isvalidatePhone}],
          smsCode: [{required: true, trigger: 'blur', message: '请输入验证码'}],
          companyName: [{required: true, trigger: 'blur',message: '请输入公司名称'}],
          diQuIds:[{required: true,message: '此项必填', trigger: 'change'},],
          regAddress:[{required: true,message: '请输入注册地址', trigger: 'blur'},],
          licenseCode:[{required: true,message: '请输入统一信号码',trigger: 'change'},],
      },
      diQuIds:[],
      options:[],
      cms:'新增客户'

    }
  },
  computed: {
    ...mapGetters([
      'name',
      'mobile',
      'userId'
    ]),
  },
  components : {

  },

  created() {

  },

  filters: {

  },
  methods:{
    getCompanyInfo(){
      const data = JSON.parse(JSON.stringify(this.sendForm8))
      if(data.companyName && data.companyName != ''){
        getCustomerCheckData({companyName:data.companyName}).then(res=>{
          this.sendForm8.licenseCode = res.licenseCode
      }).catch(err=>{
        Message.err('此企业不存在')
      })
      }
    },
    //新增联系人
    addContact(){
      this.sendForm8.contactsData.push(JSON.parse(JSON.stringify(defaultContactsItems)))
    },
    //删除联系人
    delContact(index){
      this.sendForm8.contactsData.splice(index,1)
    },

      //新增收货地址
    addAddress(){
      this.sendForm8.addressData.push(JSON.parse(JSON.stringify(defaultAddressItems)))
    },
    //删除收货地址
    delAddress(index){
      this.sendForm8.addressData.splice(index,1)
    },


    // 获取省市区列表
    getAddressListData(){
      getAreaList().then((res)=>{
        this.options = res;
      })
    },
    //显示新增客户
   async showPop8(item){
      this.sendForm8=JSON.parse(JSON.stringify(defaultSendForm8))
      this.diQuIds = []
      this.cms = '新增客户'
      this.sendForm8.companyId = ''
      await this.getAddressListData()

      if(item){
      this.cms = '编辑客户'
      const data = {companyId:item.company_id}
      await customerDetail(data).then(res=>{
      this.sendForm8.companyId=res.companyId
      this.sendForm8.companyName=res.company.company_name
      this.sendForm8.licenseCode=res.company.license_code
      this.sendForm8.regAddress=res.company.reg_address
      this.sendForm8.regPhone=res.company.reg_phone
      this.sendForm8.bankName=res.company.bank_name
      this.sendForm8.bankNumber=res.company.bank_number
      this.sendForm8.provinceId=res.company.province_id
      this.sendForm8.cityId=res.company.city_id
      this.sendForm8.areaId=res.company.area_id
      this.sendForm8.areaInfo=res.company.area_info
      this.diQuIds = [res.company.province_id,res.company.city_id,res.company.area_id]
      res.contactsData.forEach(item=>{
        const data = JSON.parse(JSON.stringify(defaultContactsItems))
        Object.keys(data).forEach(item1=>{
          data[item1] = item[item1]?item[item1]:data[item1]
        })
        this.sendForm8.contactsData.push(data)
      })
      res.addressData.forEach(item=>{
        const data = JSON.parse(JSON.stringify(defaultAddressItems))
        Object.keys(data).forEach(item1=>{
          data[item1] = item[item1]?item[item1]:data[item1]
        })
        data.diQuIds = [item.province_id,item.city_id,item.area_id]

        this.sendForm8.addressData.push(data)
      })
      })
      }else {
        this.addContact()
        this.addAddress()
      }
      this.dialogVisible8 = true;
    },
    //关闭新增客户
    handleClose8(){
      this.dialogVisible8 = false;
      this.sendForm8=JSON.parse(JSON.stringify(defaultSendForm8))
      this.diQuIds = []
    },

    //确认新增客户
    handleConfirm8(){
      this.$refs.sendForm8.validate((valid) => {
              if(this.sendForm8.contactsData.length == 0){
                this.$message.error('请添加联系人');
                  return false
              }
              if(this.sendForm8.addressData.length == 0){
                this.$message.error('收货地址');
                return false
              }
              if (valid) {
                      this.btnLoading = true;
                      let data = JSON.parse(JSON.stringify(this.sendForm8))
                      data.addressData.forEach((item,index)=>{
                        item.province_id = item.diQuIds[0] ? item.diQuIds[0] : '';
                        item.city_id = item.diQuIds[1] ? item.diQuIds[1] : '';
                        item.area_id = item.diQuIds[2] ? item.diQuIds[2] : '';
                        const areaData = this.$refs['areaInfo'+index].getCheckedNodes()
                        item.area_info = areaData?areaData[0].pathLabels.join(""):''
                        delete item.diQuIds
                      })
                      data.provinceId = this.diQuIds[0] ? this.diQuIds[0] : '';
                      data.cityId = this.diQuIds[1] ? this.diQuIds[1] : '';
                      data.areaId = this.diQuIds[2] ? this.diQuIds[2] : '';
                      data.areaInfo = this.$refs['diQuIds'].getCheckedNodes()[0]?this.$refs['diQuIds'].getCheckedNodes()[0].pathLabels.join(""):''

                       addCustomer(data).then(()=>{
                        Message.success('更新客户成功')
                          this.btnLoading = false;
                          this.dialogVisible8 = false;
                          this.sendForm8=JSON.parse(JSON.stringify(defaultSendForm8))
                          this.diQuIds= []
                          this.$emit('update')
                      }).catch(()=>{
                          this.btnLoading = false;
                      })
                  }else{
                    this.$message.error('没有通过必填验证');
                  }
                })
    },

  },
}
</script>

<style  lang="scss">

</style>
